import React, { Component } from 'react';
import Taro, { getCurrentInstance } from '@tarojs/taro';
import { View, Image, Text } from '@tarojs/components'
import { staticUrl } from '@/utils'
import { prevRoute } from '@/utils/global'
import CountDown from '@/components/CountDown'
import { getOrderDetails, payment, vendorUserInfo } from '@/api/order'
import classnames from 'classnames'
import './index.scss'

const bar3 = staticUrl('/img/order/bar3.png')
const shalou = staticUrl('/img/order/icon-shalou.png')
const iconSuc = staticUrl('/img/order/icon-success.png')
const wechatIcon = staticUrl('/img/order/icon-wechat.png')
const alipayIcon = staticUrl('/img/order/icon-alipay.png')
const yuer = staticUrl('/img/order/icon-card.png')
const check = staticUrl('/img/order/icon-check.png')

interface State {
  details: any
  checkIndex: number
  balance: number
  loaded: boolean
  serverTime: any
  showPaySuc: boolean
}
export default class Index extends Component<any, State> {
  $instance = getCurrentInstance();
  constructor () {
    super(...arguments)
    this.state = {
      details: null,
      checkIndex: 0,
      balance: 0,
      loaded: false,
      serverTime: null,
      showPaySuc: false
    }
  }

  state: State

  UNSAFE_componentWillMount() { }
  async componentDidMount() {
		console.log('this.$instance.router.params',this.$instance.router.params)
		let params = {
			orderNumber:this.$instance.router.params.orderNumber,
		}
		// 分销年卡分享进来的需要传storeCode
		if(this.$instance.router.params.shareStoreCode){
			params.storeCode = this.$instance.router.params.shareStoreCode
		}
		let userInfoData = {}
		if(!this.$instance.router.params.platform){
			const userInfo = await vendorUserInfo(params)
			userInfoData = userInfo.data.data
		}

    const orderResult = await getOrderDetails({
      orderNumber: this.$instance.router.params.orderNumber
    })
    // console.log(serverTime)
    const serverTime = new Date(orderResult.header.Date).getTime()
    const orderData = orderResult.data.data
    this.setState({
      balance: Number(userInfoData.rechargeAmount || 0),
      details: orderData,
      loaded: true,
      serverTime
    })
  }
  UNSAFE_componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() { }
  componentDidShow() { }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }
  // 支付成功跳转
  paySuccessLink() {
    const prevRouteLink = prevRoute()
    if (prevRouteLink.indexOf('pages/order/details/index') > -1) {
      Taro.navigateBack()
      return
    }
    Taro.redirectTo({
      url: '/pages/order/details/index?orderNumber=' + this.$instance.router.params.orderNumber
    })
  }
  // 余额支付
  balancePay() {
    try {
      const { details, balance } = this.state
      const payPrice = Number(details.needPayPrice) - Number(details.realPayPrice)
      const canBalancePay = Number(balance) >= payPrice
      if (!canBalancePay) {
        Taro.showToast({
          icon: 'none',
          title: '储值金额不足支付该商品'
        })
        return
      }
      payment({
        orderNumber: this.$instance.router.params.orderNumber,
        payMethod: 'balance'
      }).then(res => {
        const data = res.data.data
        // Taro.showToast({
        //     icon: 'none',
        //     title: '支付成功',
        //     success: () => {
        //         this.paySuccessLink()
        //     }
        // })
        this.showPacSucDialog('balancePay')
      })
    } catch (e) {
      Taro.showToast({
        icon: 'none',
        title: '接口异常'
      })
      return
    }
  }
	// 支付宝支付
	alipyaPay(){
		payment({
      orderNumber: this.$instance.router.params.orderNumber,
      payMethod: 'alipay_mini',
    }).then(res => {
      const data = res.data.data
      console.log(data)
			let {appId} = data
			my.tradePay({
				// 调用统一收单交易创建接口（alipay.trade.create），获得返回字段支付宝交易号trade_no
				tradeNO: appId,
				success: (res) => {
					if(res.resultCode == '6001' ){
						Taro.showToast({
							icon: 'none',
							title: '取消支付'
						})
					}else if(res.resultCode == '9000'	){
						console.log('支付宝支付成功提示', res)
         		this.showPacSucDialog('wechatPay')
					}
				},
				fail: (res) => {
					console.log('支付失败res',res)
					Taro.showToast({
						icon: 'none',
						title: '取消支付'
					})
				}
			});

    })
	}


  // 微信支付
  wechatPay() {
    const openId = Taro.getStorageSync('IS_OPENID')
    if (!openId) {
      Taro.showToast({
        icon: 'none',
        title: '没有openid，请登录再支付!'
      })
      return
    }
    payment({
      orderNumber: this.$instance.router.params.orderNumber,
      payMethod: 'wxpay_mini',
      openId
    }).then(res => {
      const data = res.data.data
      // console.log(data)
      let {
        timeStamp,
        nonceStr,
        package: packageStr,
        signType,
        paySign
      } = data
      Taro.requestPayment({
        timeStamp,
        nonceStr,
        package: packageStr,
        signType,
        paySign,
        success: (payInfo) => {
          //   console.log('suc', payInfo)
          //   Taro.showToast({
          //     icon: 'none',
          //     title: '支付成功',
          //     success: () => {
          //         this.paySuccessLink()
          //     }
          //   })
          this.showPacSucDialog('wechatPay')
        },
        fail: (error) => {
          //   console.log('err', error)
          if (error.errMsg === 'requestPayment:fail cancel') {
            Taro.showToast({
              icon: 'none',
              title: '取消支付'
            })
          }
        }
      })
    })
  }

  // 支付成功弹窗处理
  showPacSucDialog(type) {
    this.setState({
      showPaySuc: true
    })
  }

  handleToDetials() {
    this.setState({
      showPaySuc: false
    })
    const prevRouteLink = prevRoute()
    if (prevRouteLink && prevRouteLink.indexOf('pages/order/details/index') > -1) {
      Taro.navigateBack()
      return
    }
    Taro.redirectTo({
      url: '/pages/order/details/index?orderNumber=' + this.$instance.router.params.orderNumber
    })
  }

  handleToMaintainUser(){
      let path = '/maintain/index'
      Taro.navigateTo({
          url: `/pages/webview/index/index?path=${path}`
      })
  }

  handleToBooking() {
    this.setState({
      showPaySuc: false
    })

    const prevRouteLink = prevRoute()
    if (prevRouteLink && prevRouteLink.indexOf('pages/order/details/index') > -1) {
      Taro.navigateBack()
      return
    }
    const { details } = this.state
    let { orderNumber, items } = details
    let goods = []
    if (items) {
      goods = items.goods.map(v => {
        const { goodsId, goodsSkuId, number, type } = v
        return {
          goodsId,
          goodsSkuId,
          number,
          type
        }
      })
    }
    Taro.redirectTo({
      url: `/pages/order/details/index?orderNumber=${orderNumber}&order=${JSON.stringify(goods)}`
    })
  }

  toPay() {
    const { checkIndex } = this.state
    if (checkIndex === 0) {
      // 微信支付
			if(process.env.TARO_ENV === 'weapp'){
				this.wechatPay()
			}else{
				this.alipyaPay()
			}

    }
    if (checkIndex === 1) {
      // 余额支付
      this.balancePay()
    }
  }

  changePayMethod(index: number) {
    const { details, checkIndex, balance } = this.state
    const payPrice = Number(details.needPayPrice) - Number(details.realPayPrice)
    const canBalancePay = Number(balance) >= payPrice
    if (index === 1 && !canBalancePay) return
    if (checkIndex === index) return
    this.setState({
      checkIndex: index
    })
  }

  render() {
    const { loaded, details, checkIndex, balance, serverTime, showPaySuc } = this.state
    let canBalancePay = false
    let payPrice = 0
    if (details) {
      payPrice = Number(details.needPayPrice) - Number(details.realPayPrice)
      canBalancePay = Number(balance) >= payPrice
    }
    let paySuccessDialogView = details && details.type != 1 ? (<View className='pay-success-dialog'>

      <View className='content'>
        <View className='mask' onClick={this.handleToDetials.bind(this)}></View>
        <View className='content-wrap'>
          <View className='content-wrap-h'>
            <Image className='icon' src={iconSuc}></Image>
            <View className='content-wrap-h-r'>
              <Text className='text1'>支付成功</Text>
              <Text className='text2'>感谢您的购买！</Text>
            </View>
          </View>
          <View className='content-wrap-tips'>
            为了节省您到店等待时间，请提前预约
          </View>
          <View className='content-wrap-action'>
						{
							details.type !=20 ? (
								<View onClick={this.handleToBooking.bind(this)} className='content-wrap-action-btn'>
									去预约
								</View>
							) : (
								<View onClick={this.handleToMaintainUser.bind(this)} className='content-wrap-action-btn'>
									去使用
								</View>
							)
						}
						{
							details.type !=20 ? (
								<View onClick={this.handleToDetials.bind(this)} className='content-wrap-action-btn2'>
								以后再说
							</View>
							) : null
						}
          </View>
        </View>
      </View>
    </View>) : (<View className='pay-success-dialog'>

      <View className='content'>
        <View className='mask' onClick={this.handleToDetials.bind(this)}></View>
        <View className='content-wrap'>
          <View className='content-wrap-h'>
            <Image className='icon' src={iconSuc}></Image>
            <View className='content-wrap-h-r'>
              <Text className='text1'>支付成功</Text>
              <Text className='text2'>感谢您的购买！</Text>
            </View>
          </View>
        </View>
      </View>
    </View>)
    return loaded && (
      <View className='payment-main'>
        {showPaySuc && paySuccessDialogView}
        <View className='bar-wrap'>
          <Image className='bar' src={bar3}></Image>
          <View className='status-row'>
            <View className='status'>
              <Image className='shalou' src={shalou}></Image>
              {details.businessStatusLabel}
            </View>
            <View className='time'>支付剩余：<CountDown serverTime={serverTime} time={details.createdAt} /></View>
          </View>
          <View className='price'>应付金额：<View className='strong'>￥{payPrice.toFixed(2)}</View></View>
        </View>
        <View className='title'>选择付款方式</View>
				{
					process.env.TARO_ENV === 'weapp' ? (
						<View onClick={() => this.changePayMethod(0)} className={classnames('list', checkIndex === 0 && 'act')}>
							<Image className='icon' src={wechatIcon}></Image>
							<View className='content'>微信支付</View>
							<Image className='check' src={check}></Image>
						</View>
					) : (
						<View onClick={() => this.changePayMethod(0)} className={classnames('list', checkIndex === 0 && 'act')}>
							<Image className='icon' src={alipayIcon}></Image>
							<View className='content'>支付宝支付</View>
							<Image className='check' src={check}></Image>
						</View>
					)
				}


				{
					balance != 0 ?
					(<View onClick={() => this.changePayMethod(1)} className={classnames('list', !canBalancePay && 'gray', checkIndex === 1 && 'act')}>
					 <Image className='icon yuer' src={yuer}></Image>
					 <View className='content'>
						 <View className='name'>余额支付</View>
						 <View className='sub-name'>当前余额: ￥{balance.toFixed(2)}</View>
					 </View>
					 <Image className='check' src={check}></Image>
				 </View>): null
				}

        <View onClick={this.toPay.bind(this)} className='pay-btn'>去支付</View>
      </View>
    )
  }
}
